import { PrismaClient } from '@prisma/client';
import bcrypt from 'bcrypt';
import { createInterface } from 'readline';

const prisma = new PrismaClient();

const rl = createInterface({
  input: process.stdin,
  output: process.stdout,
});

function question(query) {
  return new Promise(resolve => rl.question(query, resolve));
}

async function resetPassword() {
  try {
    console.log('\n=== 重置用户密码 ===\n');
    
    // 输入用户标识
    const identifier = await question('请输入用户名或邮箱: ');
    
    // 查找用户
    const user = await prisma.user.findFirst({
      where: {
        OR: [
          { username: identifier },
          { email: identifier },
        ],
      },
    });
    
    if (!user) {
      throw new Error('用户不存在');
    }
    
    console.log(`\n找到用户: ${user.username} (${user.email})`);
    console.log(`角色: ${user.role}`);
    console.log(`状态: ${user.isActive ? '活跃' : '禁用'}\n`);
    
    const confirm = await question('确定要重置此用户的密码吗？(y/N): ');
    if (confirm.toLowerCase() !== 'y') {
      console.log('已取消');
      process.exit(0);
    }
    
    // 输入新密码
    const newPassword = await question('请输入新密码 (至少8个字符): ');
    if (newPassword.length < 8) {
      throw new Error('密码至少8个字符');
    }
    
    const confirmPassword = await question('确认新密码: ');
    if (newPassword !== confirmPassword) {
      throw new Error('两次密码输入不一致');
    }
    
    // 更新密码
    console.log('\n正在更新密码...');
    const passwordHash = await bcrypt.hash(newPassword, 10);
    
    await prisma.user.update({
      where: { id: user.id },
      data: {
        passwordHash,
        loginAttempts: 0,
        lockedUntil: null,
      },
    });
    
    // 删除所有会话（强制重新登录）
    await prisma.userSession.deleteMany({
      where: { userId: user.id },
    });
    
    console.log('\n✓ 密码重置成功！');
    console.log('  所有会话已清除，用户需要重新登录');
    console.log('  请妥善保管新密码！\n');
    
  } catch (error) {
    console.error('\n❌ 重置失败:', error.message);
    process.exit(1);
  } finally {
    rl.close();
    await prisma.$disconnect();
  }
}

resetPassword();

